package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.domain.StatementItem;
import cn.wolfcode.car.business.mapper.StatementItemMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.query.StatementItemQuery;
import cn.wolfcode.car.business.service.IStatementItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

@Service
public class StatementItemServiceImpl implements IStatementItemService {
    @Autowired
    private StatementItemMapper statementItemMapper;

    @Autowired
    private StatementMapper statementMapper;

    @Override
    public TablePageInfo<StatementItem> query(Long statementId, StatementItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(),qo.getPageSize());
        return new TablePageInfo<>(statementItemMapper.queryByStatementId(statementId,qo));
    }

    @Override
    public void saveItems(Long statementId, StatementItemQuery qo) {
        Statement statement = statementMapper.selectByPrimaryKey(statementId);
        // 非消费中状态保存 报错
        if (!Statement.STATUS_CONSUME.equals(statement.getStatus())) {
            throw new BusinessException("非法操作");
        }

        // 获取折扣金额
        BigDecimal discountAmount = qo.getDiscountAmount();

        // 获取总金额、总服务项数量
        List<StatementItem> list = qo.getList();
        BigDecimal totalAmount = new BigDecimal("0");
        BigDecimal totalQuantity = new BigDecimal("0");
        for (StatementItem statementItem : list) {
            BigDecimal multiplicand = new BigDecimal(statementItem.getItemQuantity().toString());
            totalAmount = totalAmount.add(statementItem.getItemPrice().multiply(multiplicand).setScale(2, RoundingMode.HALF_UP));
            totalQuantity = totalQuantity.add(new BigDecimal(statementItem.getItemQuantity().toString()));
        }

        // 修改结算单-服务单项 关系表
        statementItemMapper.deleteByStatementId(statementId);
        for (StatementItem statementItem : list) {
            statementItemMapper.insert(statementItem);
        }

        // 修改结算单 总金额、总服务项数量、折扣金额
        statementMapper.saveAmount(statementId,totalAmount,totalQuantity,discountAmount);
    }
}
